package com.javaspeak.designpatterns.go4.behavioural.interpreter;

import java.util.List;
import java.util.StringTokenizer;

/**
 * Used for parsing insert "Object Query Language (oql)" statements.
 *
 * @author John Dickerson
 */
public class InsertExpression extends AbstractExpression {

    private String insertStatement;


    /**
     * Insert statement is passed through the consructor
     *
     * @param insertStatement insert statement to be parsed and executed
     */
    public InsertExpression( String insertStatement ){

        this.insertStatement = insertStatement;
    }


    /* (non-Javadoc)
     * @see com.javaspeak.designpatterns.go4.behavioural.interpreter.
     *      AbstractExpression#interpret(com.javaspeak.designpatterns.go4.
     *          behavioural.interpreter.InterpreterContext)
     */
    @Override
    public List<Value> interpret(InterpreterContext context) throws Exception {

        // tokenize statement using spaces and commas as seperators
        StringTokenizer wordTokenizer =
            new StringTokenizer( insertStatement,", " );

        // the first token is "insert"
        wordTokenizer.nextToken();

        // the second token is "into"
        wordTokenizer.nextToken();

        // the third token is the className of the object we wish to insert into
        String className = wordTokenizer.nextToken();

        String valuePair;

        StringTokenizer pairTokenizer;
        String fieldName;
        String fieldValue;

        // we assume that all remaining tokens have the form:
        // fieldName=fieldValue.  We also assume that fieldValue do not have
        // spaces
        while ( wordTokenizer.hasMoreTokens() &&
                ( valuePair = wordTokenizer.nextToken() ) != null ){

            pairTokenizer = new StringTokenizer( valuePair, "=" );
            fieldName = pairTokenizer.nextToken();
            fieldValue = pairTokenizer.nextToken();
            context.setFieldValue( className, fieldName, fieldValue );
        }

        // insert statements do not return values so we return null
        return null;
    }
}
